package com.example.test.exception;

import com.example.test.common.ResponseHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
@RestController
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * 处理业务异常
	 */
	@ExceptionHandler(BusinessException.class)
	public ResponseHelper<Object> handleBusinessException(BusinessException ex) {
		return ResponseHelper.genResponse(ex.getCode(), ex.getMessage());
	}

	/**
	 * 统一处理表单数据和 JSON 请求体的参数校验异常
	 */
	@ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
	public ResponseHelper<Object> handleValidationExceptions(Exception ex) {
		List<String> errors;
		String errorMessage;
		if (ex instanceof BindException) {
			errors = ((BindException) ex).getBindingResult().getFieldErrors()
					.stream().map(FieldError::getDefaultMessage)
					.collect(Collectors.toList());
		} else {
			errors = ((MethodArgumentNotValidException) ex).getBindingResult().getFieldErrors()
					.stream().map(FieldError::getDefaultMessage)
					.collect(Collectors.toList());
		}
		if (!errors.isEmpty()) {
			errorMessage = errors.get(0);
		} else {
			errorMessage = String.join("; ", errors);
		}
		return ResponseHelper.genResponse(HttpStatus.BAD_REQUEST.value(), errorMessage);
	}

	/**
	 * 兜底异常处理，防止漏掉其他未捕获的异常
	 */
	@ExceptionHandler(Exception.class)
	public ResponseHelper<Object> handleGlobalException(Exception ex) {
		log.error("error: {}", ex.getMessage());
		return ResponseHelper.genResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统错误");
	}
}